package middleware

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"saleforce/sf-backend-gateway/i18n"
	sr "saleforce/sf-backend-user/service"
	pr "saleforce/sf-common/protoc/backend-user"
	"saleforce/sf-common/utils"
)
import cst "saleforce/sf-common/constant"
import resp "saleforce/sf-common/response"

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader(cst.Backend_Acc_Token)
		if token == "" {
			c.AbortWithStatusJSON(http.StatusOK, resp.Resp{}.Warning(401, i18n.T("token_empty", "en")))
			return
		}
		param := pr.IsLoginParam{
			Token: token,
		}
		login, err := sr.LoginService{}.IsLogin(c, &param)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusOK, resp.Resp{}.Warning(401, err.Error()))
			return
		}
		userId := login.User.Id
		userParam := pr.StringIdParam{
			Id: userId,
		}
		user, _ := sr.UserService{}.GetUserById(c, &userParam)
		if user.User.GetStatus() != 1 {
			c.AbortWithStatusJSON(http.StatusOK, resp.Resp{}.Warning(401, "The user account is locked"))
			return
		}
		userMap := utils.StructToMap(user)
		lang := c.GetHeader("lang")
		if lang == "" {
			lang = "cn"
		}
		userMap["lang"] = lang
		c.Set(cst.Current_Login_User, userMap)
		context.WithValue(c, cst.Current_Login_User, userMap)
		c.Next()
	}
}
